﻿namespace Blaze.UI
{
    using UnityEngine;
    using UnityEngine.EventSystems;

    /// <summary>
    /// 用于转发当前游戏对象上的UI事件到<see cref="Target"/>上。
    /// </summary>
    public class ScrollRectEventPasser : MonoBehaviour
    {
        public GameObject Target;

        private EventTriggerListener mListener;

        #region MonoBehaviour Events

        private void Awake()
        {
            mListener = EventTriggerListener.Get(gameObject);
        }

        private void OnDisable()
        {
            mListener.BeginDrag.RemoveListener(onBeginDrag);
            mListener.EndDrag.RemoveListener(onEndDrag);
            mListener.Drag.RemoveListener(onDrag);
            mListener.InitializePotentialDrag.RemoveListener(onPotentialDrag);
            mListener.Scroll.RemoveListener(onScroll);
        }

        private void OnEnable()
        {
            mListener.BeginDrag.AddListener(onBeginDrag);
            mListener.EndDrag.AddListener(onEndDrag);
            mListener.Drag.AddListener(onDrag);
            mListener.InitializePotentialDrag.AddListener(onPotentialDrag);
            mListener.Scroll.AddListener(onScroll);
        }

        #endregion

        #region UI EventHandlers

        private void onBeginDrag(BaseEventData e)
        {
            if (Target != null)
                Target.SendMessage("OnBeginDrag", e);
        }

        private void onDrag(BaseEventData e)
        {
            if (Target != null)
                Target.SendMessage("OnDrag", e);
        }

        private void onEndDrag(BaseEventData e)
        {
            if (Target != null)
                Target.SendMessage("OnEndDrag", e);
        }

        private void onPotentialDrag(BaseEventData e)
        {
            if (Target != null)
                Target.SendMessage("OnInitializePotentialDrag", e);
        }

        private void onScroll(BaseEventData e)
        {
            if (Target != null)
                Target.SendMessage("OnScroll", e);
        }

        #endregion
    }
}